package com.cpr.core.rabbitmq.client.persistent;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.nio.charset.StandardCharsets;

/**
 * @author Chen Panrui
 * created at 2022/3/20 16:54
 *
 * 测试消息持久化，服务重启的时候，不会丢失
 *
 */
public class Producer {
    public static void main(String[] args) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        // 指定协议 用户名+密码+host+端口号+虚拟主机
        factory.setUri("amqp://admin:123456@106.13.89.7:5672/%2f");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        // 队列是持久化的
        channel.queueDeclare("queue.persistent", true, false, false, null);
        channel.exchangeDeclare("ex.persistent", BuiltinExchangeType.DIRECT, true, false, null);

        channel.queueBind("queue.persistent", "ex.persistent", "key.persistent");

        // 设置消息的属性=2为 持久化消息
        AMQP.BasicProperties properties = new AMQP.BasicProperties().builder().deliveryMode(2).build();

        channel.basicPublish("ex.persistent", "key.persistent", properties, "消息-你好持久化".getBytes(StandardCharsets.UTF_8));

        channel.close();
        connection.close();
    }
}
